package com.itwelkin.ssm.service;

import com.itwelkin.ssm.mapper.AdminMapper;
import com.itwelkin.ssm.model.Admin;
import com.itwelkin.ssm.model.Condition;
import com.itwelkin.ssm.system.SysException;
import com.itwelkin.ssm.utils.SystemUtils;
import org.junit.Test;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,readOnly = false)
public class AdminServicelmpl implements AdminService {
    private AdminMapper adminMapper ;


    public AdminServicelmpl(AdminMapper adminMapper) {
        this.adminMapper = adminMapper;
    }

    @Override
    public List<Admin> queryItemsList(Admin admin) {
        return null;
    }

    @Override
    public Admin login(Admin adminUser) throws SysException {
        //1 先判断是否为超级管理员
        if (adminUser.getUsername().equalsIgnoreCase("admin")){

            //检测admin的密码是否正确
            adminUser.setPassword(SystemUtils.getMD5(adminUser.getPassword()));

            //如果查到是admin就直接返回,不是admin会返回空
            return adminMapper.queryUserByUsernameAndPassword(adminUser);
        }
        //2.1 通过用户名查询对应的用户
        Admin queryAdminUserWithU = adminMapper.queryUserByUsername(adminUser.getUsername());
        //2.2 未查到当前用户时为空,说明数据库中没有该用户名,直接返回空
        if (queryAdminUserWithU == null)return null;
        //2.3 检测当前账号是否激活
        if (queryAdminUserWithU.getActiveStatus() == 0) throw new SysException("对不起,该账号尚未激活,请联系管理员");
        //2.4 检测当前账号是否授权
        if (queryAdminUserWithU.getAuthorizeStatus() == 0) throw new SysException("对不起,该账号尚未授权,请联系管理员");
        //2.5 检测当前是否为禁止登录状态
        if (queryAdminUserWithU.getLoginFailCount() >= 3){
            long result = 30-(new Date().getTime()-queryAdminUserWithU.getLoginFailTime().getTime())/1000/60;
            if (result > 0) System.out.println("请等待"+result+"分钟");
            queryAdminUserWithU.setLoginFailCount(0);
            adminMapper.updateAdminUser(queryAdminUserWithU);
        }
        //3 设置加密的密码
        adminUser.setPassword(SystemUtils.getMD5(adminUser.getPassword()));
        //3.1 通过用户名及密码查询匹配的数据
        Admin queryAdminUserWithUP = adminMapper.queryUserByUsernameAndPassword(adminUser);
        //3.2 queryAdminUserWithUP会等于空,说明数据库中的用户名与密码不匹配,直接返回空
        if (queryAdminUserWithU == null){
            //3.3 对用户进行登录失败次数以及登录失败时间的数据更新
            queryAdminUserWithU.setLoginFailCount(queryAdminUserWithU.getLoginFailCount()+1);
            queryAdminUserWithU.setLoginFailTime(new Date());
            adminMapper.updateAdminUser(queryAdminUserWithU);
            return null;
        }
        //4 到这里说明查询到了对应的用户且密码正确
        queryAdminUserWithUP.setLastLoginTime(new Date());
        //将登陆失败的次数重新设置为0,并进行数据的更新
        queryAdminUserWithUP.setLoginFailCount(0);
        adminMapper.updateAdminUser(queryAdminUserWithUP);
        //将查询到的用户返回给调用者
        return queryAdminUserWithUP;
    }

    @Override
    public void registry(Admin admin) throws SysException{
        if (adminMapper.queryUserByUsername(admin.getUsername()) != null) throw new SysException("用户已存在");

        if (adminMapper.queryEmail(admin.getEmail()) != null) throw new SysException("邮箱已存在");

        admin.setPassword(SystemUtils.getMD5(admin.getPassword()));
        admin.setRegTime(new Date());

        admin.setActiveCode((SystemUtils.getUUID()+SystemUtils.getUUID()));
        admin.setActiveStatus(0);
        admin.setAuthorizeStatus(0);
        admin.setLoginFailCount(0);
        admin.setIsVisible(1);
        //添加管理员账号
        adminMapper.addAdminUser(admin);
        //发送激活邮件
        SystemUtils.sendMail(admin.getEmail(),admin.getActiveCode());
    }


    @Override
    public Admin activeAdminUser(String code) throws SysException {
        //查不到给null 查到激活
        Admin adminUser = adminMapper.queryUserByCode(code);

        if (adminUser != null){
            if (adminUser.getActiveStatus() != 0)throw new SysException("账号已激活,请登录");

            adminUser.setActiveStatus(1);
            adminMapper.updateAdminUser(adminUser);
            return adminUser;
        }

        return null;
    }

    @Override
    public List<Admin> queryUserList() {
        return adminMapper.queryAdminUser();
    }

    @Override
    public void resendMail(String id) throws SysException {
        Admin admin = adminMapper.queryUserById(id);
        if (admin == null)throw  new SysException("请终止非法操作");

        admin.setActiveCode(SystemUtils.getUUID()+SystemUtils.getUUID());
        adminMapper.updateAdminUser(admin);
        SystemUtils.sendMail(admin.getEmail(),admin.getActiveCode());
    }

    @Override
    public boolean resendMailWithMore(String[] ids) throws SysException {
        if (ids == null)throw new SysException("对不起您的操作非法，至少选择一个");

        //查询ids数组的用户列表
        List<Admin> admins = adminMapper.queryUserByIds(ids);
        if (admins == null)throw new SysException("对不起您的操作非法，至少选择一个");
        for (Admin admin : admins){
            if (admin.getActiveStatus() == 1)return false;
        }
        //正式批量重发
        for (int i=0;i<ids.length;i ++){
            resendMail(ids[i]);
        }
        return true;
    }

    @Override
    public void authorize(String id, String opr) throws SysException {
        Admin admin = adminMapper.queryUserById(id);

        System.out.println(admin);

        if (admin == null)throw new SysException("对不起您的操作非法，至少选择一个");

        if (admin.getAuthorizeStatus()==Integer.parseInt(opr))throw new SysException("请勿重复操作");

        try {
            if (Integer.parseInt(opr)<0||Integer.parseInt(opr)>1)throw new SysException("请勿乱传数据");
        }catch (SysException e){
            //当前传入的并非数字
            throw new SysException("请勿乱传数据");
        }

        //操作权限状态
        admin.setAuthorizeStatus(Integer.parseInt(opr));
        adminMapper.updateAdminUser(admin);

    }

    @Override
    public boolean authorizeWithMore(String[] ids) throws SysException {
        if (ids == null)throw new SysException("对不起您的操作非法");

        //查询ids数组的用户列表
        List<Admin> admins = adminMapper.queryUserByIds(ids);
        if (admins == null)throw new SysException("对不起您的操作非法");
        //检查每一个用户，查看是否存在已授权的用户信息
        for (Admin admin : admins){
            if (admin.getActiveStatus() == 1)return false;
        }
        //更新数据库
        for (Admin admin : admins) {
            admin.setAuthorizeStatus(1);
            adminMapper.updateAdminUser(admin);
        }


        return true;
    }

    @Override
    public List<Admin> queryUserListWithCondition(String username, String regStart, String regEnd) {
        Condition condition = new Condition();
        Date rStart = null;
        Date rEnd = null;
        String sStart = null;
        String sEnd = null;
        if (username!=null){
            condition.setUsername("%"+username+"%");
        }
        if (regStart!=null && regStart!=""){
            regStart = regStart+":59";
            String[] ts1 = regStart.split("T");
            try {
                rStart = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss").parse(ts1[0]+ts1[1]);
                sStart = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(rStart);
                condition.setRegStart(sStart);
            }catch (ParseException e){
                e.printStackTrace();
            }
        }
        if (regEnd!=null&&regEnd!=""){
            regEnd=regEnd+":59";
            String[] ts2 = regEnd.split("T");
            try {
                rEnd = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss").parse(ts2[0]+ts2[1]);
                sEnd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(rEnd);
                condition.setRegEnd(sEnd);
            }catch (ParseException e){
                e.printStackTrace();
            }
        }
        System.out.println(condition);
        return adminMapper.queryUserByCondition(condition);
    }

}
